/*
 * Copyright (c) 2025 Huawei Device, Inc. Ltd. and <马弓手>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "FilePath.h"
#include "cJSON.h"
#include "FileCache.h"
#include <filemanagement/file_uri/oh_file_uri.h>

REGISTER_PLUGIN_CLASS(FilePath)
bool FilePath::execute(const string&  action, cJSON* args, CallbackContext cbc) 
{
    if(action == "resolveNativePath") {
        if(cJSON_GetArraySize(args) > 0) {
            cJSON* pJson = cJSON_GetArrayItem(args, 0);
            if(pJson->type == cJSON_String) {
                string strUri = pJson->valuestring;
                char *pathResult = NULL;
                FileManagement_ErrCode ret = OH_FileUri_GetPathFromUri(strUri.c_str(), strUri.length(), &pathResult);
                if (ret == 0 && pathResult != NULL) {
                    if(FileCache::IsFile(pathResult, "")) {
                        cbc.success(pathResult);
                    } else {
                        cJSON* pRet = cJSON_CreateObject();
                        cJSON_AddNumberToObject(pRet, "code", 0);
                        cJSON_AddStringToObject(pRet, "message", "File does not exist");
                        cbc.error(pRet);
                        cJSON_Delete(pRet);
                    }
                    free(pathResult);
                } else {
                    cJSON* pRet = cJSON_CreateObject();
                    cJSON_AddNumberToObject(pRet, "code", 0);
                    cJSON_AddStringToObject(pRet, "message", "Unable to resolve filesystem path");
                    cbc.error(pRet);
                    cJSON_Delete(pRet);
                }
            }
        }
        return true;
    }
    
    cJSON* pRet = cJSON_CreateObject();
    cJSON_AddNumberToObject(pRet, "code", 1);
    cJSON_AddStringToObject(pRet, "message", "Invalid action");
    cbc.error(pRet);
    cJSON_Delete(pRet);
    return true;
}